#  coding=utf-8
from .. import db

from .base import BaseModel


class AccessRecord(BaseModel):
    __tablename__ = 'access_record'
    id = db.Column(db.BIGINT, primary_key=True)
    club_id = db.Column(db.BIGINT, db.ForeignKey('club.id'), doc='俱乐部')
    club_author_id = db.Column(db.Integer, db.ForeignKey('user.id'), doc='俱乐部所属者id')
    access_club = db.relationship('Club', foreign_keys=club_id,  backref=db.backref('access_records'))
    accessor_id = db.Column(db.Integer, db.ForeignKey('user.id'), doc='访问者id')
    accessor = db.relationship('User', foreign_keys=accessor_id, backref=db.backref('access_records'))

    def __init__(self, **kwargs):
        super(AccessRecord, self).__init__(**kwargs)

    def __repr__(self):
        return '<AccessLog %r>' % self.id

    @staticmethod
    def insert_record(club, accessor_id):
        try:
            record = AccessRecord(
                club_id=club.id,
                club_author_id=club.author.id,
                accessor_id=accessor_id
            )
            db.session.add(record)
            db.session.commit()
            return True, record
        except:
            return False, None
